package com.yjhb.android.sbz.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.DataConf;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.entity.UserInfo;
import com.yjhb.android.sbz.manager.im.IMManager;
import com.yjhb.android.sbz.tool.ChannelUtil;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.InvitationCodeTool;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.tool.wx.WxLogin;
import com.yjhb.android.sbz.v2.activity.V2LoginBindTelActivity;
import com.yjhb.android.sbz.v2.dialog.ContactCustomerDialog;
import com.yjhb.android.sbz.v2.mvp.presenter.V2WxLoginPresenter;
import com.yjhb.android.sbz.v2.mvp.view.V2WxLoginView;
import com.jojo.android.zxlib.tool.Global;
import com.jojo.android.zxlib.tool.ZxDeviceTool;
import com.jojo.android.zxlib.tool.ZxSpanTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * 创建者 zx
 * 创建时间 2020/11/18 10:11
 */
public class LoginActivity extends BaseActivity<V2WxLoginPresenter> implements V2WxLoginView {
    private final String TAG = "LoginActivity";
    @BindView(R.id.protocol_tv)
    TextView protocol_tv;
    @BindView(R.id.check_iv)
    ImageView check_iv;

    private String invitationCode = null;
//    String

    @Override
    protected V2WxLoginPresenter initPresenter() {
        return new V2WxLoginPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initUI() {
        setStatusBarLightMode(true);
        try {
            CharSequence charSequence = ZxSpanTool.getClickSpan("我已详细阅读并同意《用户协议》和《隐私政策》", new ZxSpanTool.OnTextClick() {
                @Override
                public void onTextClick(String text, int startIndex) {
                    if (text.equals("《用户协议》")) {
                        Tool.startWebActivity(getActivity(), DataConf.USER_PROTOCOL, "用户协议");
                    } else if ("《隐私政策》".equals(text)) {
                        Tool.startWebActivity(getActivity(), DataConf.PRIVACY_POLICY, "隐私政策");
                    }
                }
            }, "《用户协议》", "《隐私政策》");
            charSequence = ZxSpanTool.getHighlightSpan(charSequence, Color.parseColor("#48B1F1"),
                    "《用户协议》", "《隐私政策》");
            protocol_tv.setMovementMethod(LinkMovementMethod.getInstance());
            protocol_tv.setText(charSequence);
        } catch (Exception e) {
            e.printStackTrace();
        }
        check_iv.setSelected(true);
    }

    @Override
    protected void initData() {
        invitationCode = ChannelUtil.INSTANCE.getChannelNumber(this);
    }

    @Override
    protected void regEvent() {

    }


    @OnClick({R.id.check_iv, R.id.protocol_tv})
    void protocol() {
        check_iv.setSelected(!check_iv.isSelected());
        check_iv.setImageResource(check_iv.isSelected() ? R.mipmap.icon_selected : R.mipmap.icon_unselected);
    }

    @OnClick(R.id.kefu_tv)
    void kefu() {
        try {
            String url = "mqqwpa://im/chat?chat_type=wpa&uin=2173766041";
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } catch (Exception e) {
            ContactCustomerDialog customerDialog = new ContactCustomerDialog(this);
            customerDialog.show();
        }
    }

    /**
     * 权限
     */
    void requestPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.READ_PHONE_STATE)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {

                    }
                });
    }

    /*
    接收全局消息
    */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(EventMsg eventMsg) {
        if (eventMsg.msg == EventMsg.USER_WX_RESULT) {
            SendAuth.Resp resp = (SendAuth.Resp) eventMsg.object;
            if (resp != null && resp.errCode == BaseResp.ErrCode.ERR_OK) {
//                presenter.wxLogin(resp.code, invitationCode,
//                        ZxDeviceTool.getAndroidId(this));
                presenter.verifyBindPhone(resp.code);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //从剪切板获取邀请码
        Global.getInstance().getMainHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(invitationCode))
                    invitationCode = InvitationCodeTool.getInvitationCode();
            }
        }, 200);
    }


    public void onPhoneLogin(View view) {
        new QMUIBottomSheet
                .BottomListSheetBuilder(getActivity(), false)
                .addItem(R.mipmap.phone, "手机号登录", "")
                .addItem(R.mipmap.account, "账号登录", "")
                .setTitle("其他方式")
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        if (position == 0) {
                            startActivity(new Intent(getActivity(), PhoneLoginActivity.class));
                            dialog.dismiss();
                        } else if (position == 1) {
                            startActivity(new Intent(getActivity(), LoginAccountActivity.class));
                            dialog.dismiss();
                        }
                    }
                })
                .build()
                .show();
    }

    public void onLogin(View view) {
        if (check_iv.isSelected()) {
            WxLogin.login();
        } else {
            ZxToast.showCenterToast("请详细阅读并同意《用户协议》和《隐私政策》");
        }
    }

    @Override
    public void onFailure(int code, String msg) {
        loadingDialog.cancel();
        ZxToast.showCenterToastLight(msg);
    }

    @Override
    public void onLoginSuccess(UserInfo userInfo) {
        loadingDialog.cancel();
        App.updateUserInfo(userInfo);
        App.updateUUID(userInfo.getUuid());
        IMManager.getInstance().login();
        EventBus.getDefault().post(new EventMsg(EventMsg.LOGIN_SUCCESS, 1));
        if (userInfo.getParentId() == null && !TextUtils.isEmpty(invitationCode)) {
            EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_BIND_INVITE_CODE, invitationCode));
        }
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Override
    public void telVerify(@Nullable String tel, @Nullable String openid) {
        if (TextUtils.isEmpty(tel)) {
            Intent intent = new Intent(this,V2LoginBindTelActivity.class);
            intent.putExtra("openid",openid);
            startActivity(intent);
        } else {
            presenter.newWxLogin(openid, ZxDeviceTool.getAndroidId(this));
        }
    }

    @Override
    public void loggingIn() {
        loadingDialog.show();
    }
}
